package cn.com.wangluotongxin.linux.service.impl;

import cn.com.wangluotongxin.common.constants.CommonConstant;
import cn.com.wangluotongxin.common.exceptions.BadResponseException;
import cn.com.wangluotongxin.linux.form.SendCommandForm;
import cn.com.wangluotongxin.linux.service.ICommandService;
import cn.com.wangluotongxin.linux.service.IFileService;
import cn.com.wangluotongxin.linux.vo.CommandResultVo;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class CommandServiceImpl implements ICommandService {

    @Autowired
    private IFileService fileService;

    private final static  List<String> commands = Arrays.asList("cd", "ls", "touch", "rm", "nginx", "docker");

    @Override
    public CommandResultVo sendCommand(SendCommandForm form) {
        if(!commands.contains(form.getCommand())){
            return new CommandResultVo()
                    .setStatus(CommonConstant.ZERO)
                    .setResult(String.format("-bash: %s: command not found", form.getCommand()))
                    .setFolderPath(form.getFolderPath())
                    .setFolderName(new File(form.getFolderPath()).getName());
        }
        if(form.getCommand().equals("cd")) {
            return this.sendCommandCd(form.getFolderPath(), form.getContent());
        }
        return this.sendCommand(form.getFolderPath(), form.getContent());
    }

    private CommandResultVo sendCommand(String folderPath, String command) {
        if(!Files.exists(Paths.get(folderPath))) {
            throw new BadResponseException("命令路径访问失败");
        }
        try {
            String commandResult = this.startSendCommand(folderPath, command);
            return new CommandResultVo()
                    .setStatus(CommonConstant.ONE)
                    .setResult(commandResult)
                    .setFolderPath(folderPath)
                    .setFolderName(new File(folderPath).getName());
        }catch (Exception ex) {
            ex.printStackTrace();
            log.info("执行{}指令异常:{}", command, ex.getMessage());
            return new CommandResultVo()
                    .setStatus(CommonConstant.ZERO)
                    .setResult(ex.getMessage())
                    .setFolderPath(folderPath)
                    .setFolderName(new File(folderPath).getName());
        }
    }

    private CommandResultVo sendCommandCd(String folderPath, String content) {
        if(!Files.exists(Paths.get(folderPath))) {
            throw new BadResponseException("命令路径访问失败");
        }
        String commandContent = Arrays.asList(content.split(" ")).get(Arrays.asList(content.split(" ")).size() - 1);
        if(commandContent.startsWith("/")) {
            commandContent = "/root" + commandContent;
            folderPath = commandContent;
        } else {
            commandContent = folderPath+ commandContent;
            folderPath = folderPath + "/" + commandContent;
        }
        if(!Files.exists(Paths.get(commandContent))) {
            return new CommandResultVo()
                    .setStatus(CommonConstant.ZERO)
                    .setResult(String.format("-bash: cd: %s: No such file or directory", content))
                    .setFolderPath(folderPath)
                    .setFolderName(new File(folderPath).getName());
        }
        if(!Files.isDirectory(Paths.get(commandContent))) {
            return new CommandResultVo()
                    .setStatus(CommonConstant.ZERO)
                    .setResult(String.format(" -bash: cd: %s: Not a directory", content))
                    .setFolderPath(folderPath)
                    .setFolderName(new File(folderPath).getName());
        }
        return new CommandResultVo().setStatus(CommonConstant.ONE).setFolderPath(commandContent).setFolderName(new File(commandContent).getName());
    }

    private String startSendCommand(String folderPath, String command) {
        if(folderPath.startsWith("/root") || folderPath.startsWith("root")) {
            if(folderPath.startsWith("/root")) {
                folderPath = folderPath.replace("/root", "");
            } else {
                folderPath = folderPath.replace("root", "");
            }
        }
        StringBuilder fileContent = new StringBuilder();
        if(StrUtil.isNotBlank(folderPath)) {
            fileContent.append(folderPath);
            fileContent.append("&");
        }
        fileContent.append(command);
        log.info("发送指令:{}", fileContent);
        fileService.writeFile("/root/home/cmd/command", "cmd_command", fileContent.toString());
        ThreadUtil.sleep(1000);

        Object fileReadContent = fileService.readFile("/root/home/cmd/output", "command_response");
        return String.valueOf(fileReadContent);
    }
}
